package com.example.springmvcproject.Controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.example.springmvcproject.Pojo.User;
import com.example.springmvcproject.Service.Inteface.UserService;
import com.example.springmvcproject.Utils.ResultCode;
import com.example.springmvcproject.Utils.ResultMessage;
import com.example.springmvcproject.Utils.SaTokenUtils;
import com.example.springmvcproject.Vo.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping("/login")
    public ResultMessage getLoginToken(@RequestBody @Validated UserVo userVo){
        return userService.getLoginByAccountAndPassword(userVo);
    }


    @RequestMapping("/register")
    public ResultMessage insertUser(@RequestBody @Validated UserVo userVo){
        return userService.insertUser(userVo);
    }
    @SaCheckLogin
    @RequestMapping("/updatePassword")
    public ResultMessage updateUserPassword(@RequestBody @Validated UpdatePasswordVo updatePasswordVo){
        return userService.updatePassword(updatePasswordVo);
    }
    @SaCheckLogin
    @SaCheckRole({"1"})
    @RequestMapping("/selectUsersBySelective")
    public ResultMessage selectUsersBySelective(@RequestBody @Validated UserSelectiveVo userSelectiveVo){
        return userService.selectUsersBySelective(userSelectiveVo);
    }

    @SaCheckLogin
    @SaCheckRole({"1"})
    @RequestMapping("/deleteUserByIdAndAccount")
    public ResultMessage deleteUserByIdAndAccount(@RequestBody @Validated UserDelVo userDelVo){
        return userService.deleteUserByIdAndAccount(userDelVo);
    }
    @SaCheckLogin
    @RequestMapping("/LoingOut")
    public ResultMessage loginOut(){
        StpUtil.logout();
        return new ResultMessage(ResultCode.RESULT_OK.getCode(), ResultCode.RESULT_OK.getStatus(), null,"退出成功");
    }

    @SaCheckLogin
    @RequestMapping("/loginMsg")
    public ResultMessage loginMsg(){
        SaSession sessionByHeaderToken = SaTokenUtils.getSessionByHeaderToken();
        User userMsg = (User) sessionByHeaderToken.get("userMsg");
        return new ResultMessage(ResultCode.RESULT_OK.getCode(), ResultCode.RESULT_OK.getStatus(), null,userMsg);
    }

    @SaCheckLogin
    @RequestMapping("/uploadAuthor")
    public ResultMessage uploadAuthor(@ModelAttribute @Validated UploadVo uploadVo, HttpServletRequest request) throws IOException {
        return userService.uploadAuthor(uploadVo,request);
    }

    @RequestMapping("/getTest")
    public Object getTest(){
        return StpUtil.getLoginId();
    }

}
